#define _CRT_SECURE_NO_WARNINGS 1
int dx[8] = { 0,-1,0,1,-1,-1,1,1 };
int dy[8] = { 1,0,-1,0,-1,1,1,-1 };

unordered_map<int, int> mp;
int cnt = -1;
int ans = -1;
class Solution {
public:
    bool isprim(int x) {
        for (int i = 2; i <= x / i; i++) {
            if (x % i == 0)return false;
        }
        return true;
    }
    void dfs(int x, int y, int f, int s, int n, int m, vector<vector<int>>& mat) {
        if (s > 10) {
            if (isprim(s)) {
                mp[s]++;
                if (mp[s] >= cnt) {
                    if (mp[s] > cnt) {
                        cnt = mp[s];
                        ans = s;
                    }
                    else {
                        ans = max(ans, s);
                    }

                }
            }
        }

        int a = x + dx[f];
        int b = y + dy[f];
        if (a >= 0 && a < n && b >= 0 && b < m) {
            s = s * 10 + mat[a][b];
            dfs(a, b, f, s, n, m, mat);
        }
    }

    int mostFrequentPrime(vector<vector<int>>& mat) {
        ans = -1;
        cnt = -1;
        mp.clear();
        int n = mat.size();
        int m = mat[0].size();

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                for (int k = 0; k < 8; k++) {
                    dfs(i, j, k, mat[i][j], n, m, mat);
                }
            }
        }
        //  cout<<mp[191]<<" "<<mp[19]<<endl;
        return ans;
    }
};